from flask import render_template, current_app, session, g

from info import constants
from info.models import User, News, Category
from info.utils.common import user_login_data
from . import index_blu

# 首页
@index_blu.route('/',methods=["GET","POST"])
@user_login_data
def dome():
    # # 取出session中的用户编号
    # user_id = session.get("user_id")
    #
    # # 取出用户对象
    # user = None
    # if user_id:
    #     try:
    #         user = User.query.get(user_id)
    #     except Exception as e:
    #         current_app.logger.error(e)

    # 处理热门新闻,查询前10条
    try:
        click_news = News.query.order_by(News.clicks.desc()).limit(constants.CLICK_RANK_MAX_NEWS).all()
    except Exception as e:
        current_app.logger.error(e)

    # 将新闻对象列表转成字典信息
    click_news_list = []
    for news in click_news:
        click_news_list.append(news.to_dict())

    # 获取分类数据
    try:
        categories = Category.query.all()
    except Exception as e:
        current_app.logger.error(e)

    # 将对象分类列表转成字典列表
    categories_list = []
    for category in categories:
        categories_list.append(category.to_dict())

    # 将用户的对象信息装换为字典信息
    data = {
        # 如果user存在，走左边，不存在，走右边
        "user_info": g.user.to_dict() if g.user else None,
        "click_news_list":click_news_list,
        "categories":categories_list
    }

    return render_template("news/index.html",data=data)

# 每个网站都会发送请求/favicon.ico，去自动加载logo图片
# 如果指定访问static中的内容，current_app.send_static_file(),自动寻找static中的内容，返回响应体对象
@index_blu.route('/favicon.ico')
def web_logo():
    return current_app.send_static_file('news/favicon.ico')